//
//  AnimationViewController.m
//  MyProject
//
//  Created by yun on 2018/5/7.
//  Copyright © 2018年 yun. All rights reserved.
//

#import "AnimationViewController.h"
#import "WaveView.h"

@interface AnimationViewController ()<CAAnimationDelegate>

@property(nonatomic,strong) UIView *aniView;
@property(nonatomic,strong) UIImageView *bgImgV;
@property(nonatomic,assign) NSInteger currentIndex;
@property(nonatomic,strong) WaveView *waveView;
@property(nonatomic,strong) UISlider *slider;




@end

@implementation AnimationViewController

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.waveView stopLink];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.aniView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
//    self.aniView.center = self.view.center;
//    self.aniView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:self.aniView];
//    [self coreAnimation];
    
//    [self transitionAnimation];
    [self wave];
    
}

- (void)wave{
    self.waveView = [[WaveView alloc] initWithCenter:self.view.center radius:60];
    self.waveView.percent = 0.1;
    [self.view addSubview:self.waveView];
    
    self.slider = [[UISlider alloc] init];
    [self.slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.waveView.mas_bottom).offset(50);
        make.left.mas_equalTo(50);
        make.right.mas_equalTo(-50);
        make.height.mas_equalTo(25);
    }];
    
}

- (void)sliderChange:(UISlider *)slider{
    self.waveView.percent = slider.value;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //    [self viewAnimation];
    //    [self viewAnimationWithBlocks];
    //    [self coreAnimation];
    //    UIViewController *vc = [NSClassFromString(@"MASViewController") new];
    //    [self.navigationController pushViewController:vc animated:YES];
}

- (void)transitionAnimation{
    self.bgImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"movie1.jpg"]];
    self.bgImgV.userInteractionEnabled = YES;
    _currentIndex = 1;
    self.bgImgV.frame = self.view.bounds;
    [self.view addSubview:_bgImgV];
    
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipe:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.bgImgV addGestureRecognizer:leftSwipe];
    [self.bgImgV addGestureRecognizer:rightSwipe];
    
}

#pragma mark -- 手势
- (void)leftSwipe:(UISwipeGestureRecognizer *)swipe{
    [self transitionWithSwipe:YES];
}

- (void)rightSwipe:(UISwipeGestureRecognizer *)swipe{
    [self transitionWithSwipe:NO];
}



- (void)transitionWithSwipe:(BOOL)right{
    CATransition *trans = [CATransition animation];
    trans.type = @"rippleEffect";
    if (right) {
        trans.subtype = kCATransitionFromRight;
    } else {
        trans.subtype = kCATransitionFromLeft;
    }
    trans.duration = 1;
    // 设置图片
    if (right) {
        if (_currentIndex >= 8){
            _currentIndex = 1;
        } else {
            _currentIndex++;
        }
    } else {
        if (_currentIndex <= 1){
            _currentIndex = 8;
        } else {
            _currentIndex--;
        }
    }
    self.bgImgV.image = [UIImage imageNamed:[NSString stringWithFormat:@"movie%ld.jpg",(long)_currentIndex]];
    [self.bgImgV.layer addAnimation:trans forKey:@"transitionAnimation"];
}




/**
 * ca动画是针对layer层，且动画执行后，本身view的属性并没有改变
 */
- (void)coreAnimation{
//    CABasicAnimation *baseAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
//    baseAnimation.duration = 2;
//    baseAnimation.removedOnCompletion = NO;
//    baseAnimation.fillMode = kCAFillModeForwards;
//    baseAnimation.byValue = [NSValue valueWithCGPoint:CGPointMake(200, 400)];
//    baseAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 120)];
//    baseAnimation.autoreverses = YES;
//    [self.aniView.layer addAnimation:baseAnimation forKey:@"baseAnimation"];
    
    CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.values = @[[NSValue valueWithCGPoint:CGPointMake(0, 0)],[NSValue valueWithCGPoint:CGPointMake(100, 100)],[NSValue valueWithCGPoint:CGPointMake(0, 200)]];
//    animation.duration = 2;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.keyTimes = @[@0,@0.25,@0.5,@0.75,@1];
    animation.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 100, 100)].CGPath;
    
    CABasicAnimation * animation2 = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
    animation2.toValue = @50;
//    animation2.duration = 2;
    animation2.fillMode = kCAFillModeForwards;
    animation2.removedOnCompletion = NO;
    
    CAAnimationGroup * group = [CAAnimationGroup animation];
    group.duration = 2;
    group.repeatCount = 100000;
    group.delegate = self;
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    group.animations = @[animation,animation2];
    
    [self.aniView.layer addAnimation:group forKey:@"group"];
    
}

- (void)animationDidStart:(CAAnimation *)anim{
    NSLog(@"开始%@",anim);
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    NSLog(@"结束%@",anim);
}

/**
 * UIView(UIViewAnimationWithBlocks)
 */
- (void)viewAnimationWithBlocks{
    /**
     * dampingRatio:阻尼比
     弹簧动画接近其静止状态时的阻尼比。
     要在没有振荡的情况下平滑地减速动画，请使用值1.使用接近零的阻尼比来增加振荡。
     
     velocity:速度
     初始弹簧速度。 要平滑开始动画，请将此值与附件之前的视图速度相匹配。
     值1对应于一秒内遍历的总动画距离。 例如，如果总动画距离为200点，并且您希望动画的开始与100 pt / s的视图速度匹配，则使用值0.5。
     
     */
//    [UIView animateWithDuration:1 delay:0.5 usingSpringWithDamping:0.2 initialSpringVelocity:2 options:UIViewAnimationOptionCurveLinear animations:^{
//        self.aniView.bounds = CGRectMake(0, 0, 150, 150);
//    } completion:^(BOOL finished) {
//        self.aniView.bounds = CGRectMake(0, 0, 90, 90);
//    }];
    
    /**
     * UIViewKeyframeAnimations
     */
    [UIView animateKeyframesWithDuration:2 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeDiscrete animations:^{
        self.aniView.center = CGPointMake(40, 100);
    } completion:^(BOOL finished) {
        
    }];
    
}

/**
 * UIView动画(UIViewAnimation)
 */
- (void)viewAnimation{
    /**
     * 开始一个动画，标志和携带参数（void * 任意类型指针）
     动画属性：
     frame
     bounds
     center
     transform
     alpha
     backgroundColor
     contentStretch
     */
    void * context = @"任意指针";
    [UIView beginAnimations:@"viewAni" context:context];
    /**
     * 代理和WillStartSelector、DidStopSelector是对应的，否则Selector不会执行
     */
    [UIView setAnimationDelegate:self];
    [UIView setAnimationWillStartSelector:@selector(animationDidStart:context:)];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    [UIView setAnimationDuration:1];
//    [UIView setAnimationDelay:1];
//    [UIView setAnimationStartDate:[NSDate date]];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatCount:1];
    //    [UIView setAnimationRepeatAutoreverses:YES];
    //    [UIView setAnimationBeginsFromCurrentState:YES];
    //    self.aniView.bounds = CGRectMake(0, 0, 150, 150);
    // 这个需要布局后才能触发（加个触发事件）
    //    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.aniView cache:YES];
    
    
//
    /**
     * CGAffineTransform:矩阵
                           |a  b  0|
     [x' y' 1] = [x y 1] X |c  d  0|
                           |tx ty 0|
     x' = ax+cy+tx; y' = bx+dy+ty;
     x',y'是矩阵变化后的值
     struct CGAffineTransform {
     CGFloat a, b, c, d;
     CGFloat tx, ty;
     };
     CGAffineTransformIdentity：标准矩阵，没有变化
     CGAffineTransformMake：自定义变化
     */
    // 平移
//    self.aniView.transform = CGAffineTransformMakeTranslation(50, 50);
    // 缩放
//    self.aniView.transform = CGAffineTransformMakeScale(1.3, 1.3);
    /**
     *CGAffineTransformMakeRotation
     t' = [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ]
     */
    self.aniView.transform = CGAffineTransformMakeRotation(M_PI_2);

    // 结束动画
    [UIView commitAnimations];
}

- (void)animationDidStart:(NSString *)animationID context:(void *)context{
    NSLog(@"start:%@===%@",animationID,context);
}
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    NSLog(@"stop:%@===%@===%@",animationID,finished,context);
}


- (void)introduceLayer{
//    self.view.layer.backgroundColor = UIColor.orangeColor.CGColor;
//    self.view.layer.cornerRadius = 20.f;
//    self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);
    
//    CALayer *layer1 = [CALayer layer];
//    layer1.frame = CGRectMake(100, 100, 100, 100);
//    layer1.backgroundColor = [UIColor orangeColor].CGColor;
//    layer1.shadowColor = [UIColor blackColor].CGColor;
//    layer1.shadowOffset = CGSizeMake(0, 3);
//    layer1.shadowRadius = 5;
//    layer1.shadowOpacity = 1;
//    [self.view.layer addSublayer:layer1];
    
    CALayer *layer2 = [CALayer layer];
    layer2.frame = CGRectMake(100, 100, 100, 100);
    UIImage *imgV = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/cat.jpeg",[NSBundle mainBundle].resourcePath]];
    layer2.contents = (__bridge id _Nullable)(imgV.CGImage);
    layer2.borderColor = [UIColor blackColor].CGColor;
    layer2.borderWidth = 2;
    [self.view.layer addSublayer:layer2];
}

/**
 * CGAffineTransform:矩阵
                       |a  b  0|
 [x' y' 1] = [x y 1] X |c  d  0|
                       |tx ty 0|
 x' = ax+cy+tx; y' = bx+dy+ty;
 x',y'是矩阵变化后的值
 struct CGAffineTransform {
 CGFloat a, b, c, d;
 CGFloat tx, ty;
 };
 CGAffineTransformIdentity：标准矩阵，没有变化
 CGAffineTransformMake：自定义变化
 */
// 平移
//    self.aniView.transform = CGAffineTransformMakeTranslation(50, 50);
// 缩放
//    self.aniView.transform = CGAffineTransformMakeScale(1.3, 1.3);
/**
 *CGAffineTransformMakeRotation
 t' = [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ]
 */

/**
 * CATransform3D:矩阵
                            |m11 m12 m13 m14|
 [x' y' z' 1] = [x y z 1] X |m21 m22 m23 m24|
                            |m31 m32 m33 m34|
                            |m41 m42 m43 m44|
 
 x' = m11x + m21y + m31z + m41;
 y' = m12x + m22y + m32z + m42;
 z' = m13x + m23y + m33z + m43;
 y' = m12x + m22y + m32z + m42;
 */

- (void)transform3d{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
